<?php
/**
 * Created by PhpStorm.
 * User: chenjunjie
 * Date: 2020/8/31
 * Time: 2:38 PM
 */
declare(strict_types = 1);
namespace App\Repositories;

use App\Model\XApprovalFlow;
use App\Model\XApprovalFlowNode;

class ApprovalFlowRepository {
    public function getRecord(array $condition){

        if(!isset($condition['pageNum'])){
            $condition['pageNum'] = 1;
        }
        if(!isset($condition['pageRow'])){
            $condition['pageRow'] = 20;
        }

        $record = XApprovalFlowNode::query()
            ->leftJoin("x_approval_flow","x_approval_flow.id","=","x_approval_flow_node.flow_id")
            ->leftJoin('x_api_user_company', function ($join)  {
                $join->on('x_api_user_company.company_id', '=', 'x_approval_flow.company_id')
                    ->on('x_api_user_company.user_id', 'x_approval_flow.add_company_user_id');
            })
            ->where("x_approval_flow_node.approver_id",$condition["companyUserId"])
            ->where("x_approval_flow_node.status",0)
            ->select("x_approval_flow_node.id as flowNodeId",
                "x_approval_flow.id",
                "x_approval_flow.step",
                "x_approval_flow.comment",
                "x_approval_flow.company_id",
                "x_approval_flow.add_company_user_id as addCompanyUserId",
                "x_approval_flow.add_time as addTime",
                "x_approval_flow.type","x_approval_flow.status",
                "x_api_user_company.nickname"
                );


        if(isset($condition['type'])){
            $type = (array)json_decode($condition['type']);
            $record->whereIn('x_approval_flow.type', $type);
        }

        if(isset($condition['applyUserId'])){

            $applyUserId = (array)json_decode($condition['applyUserId']);

            $record->where('x_approval_flow.add_company_user_id', $applyUserId);
        }
        $count = $record->count();
        $record->orderBy('x_approval_flow.id','DESC');

        $pager = $record->limit($condition['pageRow'] * ($condition['pageNum'] - 1))
            ->take($condition['pageRow'])
            ->get()
            ->toArray();


        return ['totalCount' => $count, 'flowList' => $pager];
    }

    public function getRecordCount(array $condition){
        $record = XApprovalFlowNode::query()
            ->leftJoin("x_approval_flow","x_approval_flow.id","=","x_approval_flow_node.flow_id")
            ->where('approver_id', $condition['companyUserId'])
            ->where("x_approval_flow_node.status", 0);


        if(isset($condition['type'])){
            $record->where('type', $condition['type']);
        }

        return $record->count();
    }
}